<template>
  <div class="projectList">
    <div class="main-table">
      <el-button-group>
        <el-button type="primary" icon="el-icon-plus" @click="catalogOperate('addRootCatalog')">添加根目录</el-button>
        <el-button type="primary" icon="el-icon-caret-right" @click="catalogOperate('closeCatalog')">折叠所有节点</el-button>
        <el-button type="primary" icon="el-icon-caret-bottom" @click="catalogOperate('openCatalog')">展开所有节点</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="catalogOperate('refreshCatalog')">刷新</el-button>
      </el-button-group>
      <div class="main-table-div">
        <el-table
          v-loading="loading"
          ref="catalogTree"
          :data="config.catalogTreeData"
          style="width:100%"
          row-key="id"
          lazy
          border
          :load="load"
          :tree-props="{children:'children',hasChildren:'hasChildren'}"
        >
          <el-table-column
            prop="name"
            label="名称"
            width="300px"
            align="left"
            fixed="left"
          ></el-table-column>
          <el-table-column
            prop="url"
            align="center"
            label="数据地址"
          ></el-table-column>
          <el-table-column
            prop="servicetype"
            align="center"
            width="100px"
            label="数据类型"
          ></el-table-column>
          <el-table-column
            prop="isvalid"
            align="center"
            width="100px"
            label="是否可用"
          >
            <template slot-scope="scope">
              <el-switch v-model="scope.row.isvalid===1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="operate"
            align="center"
            label="操作"
            width="280px"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.type===0">
                <el-button type="text" icon="el-icon-circle-plus-outline" size="mini"
                           @click="catalogOperate('addCatalog',scope.$index,scope.row)"
                >添加目录
                </el-button>
                |
                <el-button type="text" icon="el-icon-plus" size="mini"
                           @click="catalogOperate('addService',scope.$index,scope.row)"
                >添加服务
                </el-button>
                |
              </template>
              <el-button type="text" icon="el-icon-edit" size="mini"
                         @click="catalogOperate('edit',scope.$index,scope.row)"
              >编辑
              </el-button>
              |
              <template v-if="scope.row.type===1">
                <el-button type="text" icon="el-icon-search" size="mini"
                           @click="catalogOperate('editQuery',scope.$index,scope.row)"
                >查询
                </el-button>
                |
                <el-button type="text" icon="el-icon-s-data" size="mini"
                           @click="catalogOperate('editStatistics',scope.$index,scope.row)"
                >统计
                </el-button>
                |
              </template>
              <el-button type="text" icon="el-icon-delete" size="mini"
                         @click="catalogOperate('delete',scope.$index,scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="sort"
            align="center"
            label="排序"
            width="180px"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="catalogOperate('orderToTop',scope.$index,scope.row)">置顶
              </el-button>
              |
              <el-button type="text" size="mini" @click="catalogOperate('orderUp',scope.$index,scope.row)">上移
              </el-button>
              |
              <el-button type="text" size="mini" @click="catalogOperate('orderDown',scope.$index,scope.row)">下移
              </el-button>
              |
              <el-button type="text" size="mini" @click="catalogOperate('orderToBottom',scope.$index,scope.row)">置底
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <component :is="dialogConfig.dialogComponent" :config="dialogConfig.config" :param="dialogConfig.param"
               :form="dialogConfig.form"
    ></component>
  </div>
</template>

<script>
import qs from 'qs'
import bus from '@/utils/bus.js'
import { listResourceCatalog, sortResourceCatalog, deleteResourceCatalogItem } from '@/api/resource/resourceCatalog'
import { listDict } from '@/api/system/dict/tbportalDict'
import { listRole } from '@/api/system/role'
import * as gcf from '@/utils/Global/GlobalCommonFunction'

export default {
  name: 'resourceCatalog',
  data() {
    return {
      // 遮罩层
      loading: true,
      config: {
        catalogData: [],
        catalogTreeData: [],
        catalogDirTreeData: [],
        serviceTypes: [],
        prjTypes: []
      },
      dialogConfig: {
        dialogComponent: undefined,
        config: {
          title: '',
          show: false,
          itemShow: {},
          innerHtml: '',
          okBtnText: ''
        },
        params: {},
        form: {}
      }
    }
  },
  beforeMount() {
    this.queryServiceType({
      'queryType': 'byDictKey',
      'dictKey': 'serviceType'
    })
    this.queryPrjType({
      'queryType': 'byDictKey',
      'dictKey': 'prjType'
    })
    this.queryAllPortalRolesAjax({ 'isAllRoles': true })
    this.queryCatalog({})
  },
  mounted() {
    bus.$on('refreshResourceCatalog', msg => {
      let that = this
      that.queryCatalog({})
    })
  },
  methods: {
    /**
     * 添加目录
     * @param parentId 父节点ID
     * @param parentLevel 父节点级别
     * @param parentName 父节点名称
     * @param children 子节点
     * @constructor
     */
    addCatalogDir(parentId, parentLevel, parentName, children) {
      let that = this
      that.dialogConfig.config = {
        title: '添加目录',
        show: true,
        itemShow: {
          parentCatalog: true,
          name: true,
          isValid: true,
          roles: true
        },
        okBtnText: '添加'
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editCatalogDir.vue'], resolve)
      that.config.catalogDirTreeData = []
      let rootNode = {
        'label': '根目录',
        'name': '根目录',
        'id': '',
        'value': '',
        'children': []
      }
      that.config.catalogDirTreeData.push(rootNode)
      that.formatParentNodeTreeData(that.config.catalogDirTreeData, '', parentId, '', that.config.catalogTreeData)
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.catalogDirTreeData,
        portalRoles: that.config.portalRoles
      }
      let sortid = children.length
      for (let i in children) {
        let sortIndex = children[i]['sortid']
        if (sortid <= sortIndex) {
          sortid = sortIndex
        }
      }
      that.dialogConfig.form = {
        operatetype: 'insertDir',
        parentCatalog: parentId == null ? '' : parentId,
        parentCatalogName: parentName == null ? '根目录' : parentName,
        sortid: sortid,
        enflag:""
      }
    },
    addCatalogRootDir() {
      let that = this
      that.dialogConfig.config = {
        title: '添加根目录',
        show: true,
        itemShow: {
          parentCatalog: false,
          name: true,
          isValid: true,
          roles: true
        },
        okBtnText: '添加'
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editCatalogDir.vue'], resolve)
      that.dialogConfig.param = {
        portalRoles: that.config.portalRoles
      }
      let sortid = that.config.catalogTreeData.length
      for (let i in that.config.catalogTreeData) {
        let sortIndex = that.config.catalogTreeData[i]['sortid']
        if (sortid <= sortIndex) {
          sortid = sortIndex
        }
      }
      that.dialogConfig.form = {
        operatetype: 'insertDir',
        parentCatalog: '',
        parentCatalogName: '',
        sortid: sortid,
        enflag:""
      }
    },
    /**
     * 添加服务
     * @param parentId
     * @param parentName
     * @param children
     * @constructor
     */
    addCatalogService(parentId, parentName, children) {
      let that = this
      that.dialogConfig.config = {
        title: '添加服务',
        show: true,
        itemShow: {
          isLabel: false
        },
        okBtnText: '添加'
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editCatalogService.vue'], resolve)
      that.config.catalogDirTreeData = []
      let rootNode = {
        'label': '根目录',
        'name': '根目录',
        'id': '',
        'value': '',
        'children': []
      }
      that.config.catalogDirTreeData.push(rootNode)
      that.formatParentNodeTreeData(that.config.catalogDirTreeData, '', parentId, '', that.config.catalogTreeData)
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.catalogDirTreeData,
        portalRoles: that.config.portalRoles,
        prjTypes: that.config.prjTypes,
        serviceTypes: that.config.serviceTypes
      }
      let sortid = children.length
      for (let i in children) {
        let sortIndex = children[i]['sortid']
        if (sortid <= sortIndex) {
          sortid = sortIndex
        }
      }
      that.dialogConfig.form = {
        operatetype: 'insertService',
        parentCatalog: parentId == null ? '' : parentId,
        parentCatalogName: parentName == null ? '根目录' : parentName,
        sortid: sortid,
        legend:"",
        enflag:""
      }
    },
    /**
     * 操作按钮事件
     * @param operateType
     * @param index
     * @param row
     */
    catalogOperate(operateType, index, row) {
      let that = this
      let items = []
      switch (operateType) {
        case 'addRootCatalog'://添加根目录
          that.addCatalogRootDir()
          break
        case 'closeCatalog'://关闭所有目录
          that.$nextTick(() => {
            that.setAllExpand(that.config.catalogTreeData, false)
          })
          break
        case 'openCatalog'://打开所有目录
          that.$nextTick(() => {
            that.setAllExpand(that.config.catalogTreeData, true)
          })
          break
        case 'refreshCatalog'://刷新目录
          that.queryCatalog({})
          break
        case 'addCatalog'://添加目录节点
          that.addCatalogDir(row.id, row.level, row.name, row.children)
          break
        case 'addService'://添加服务节点
          that.addCatalogService(row.id, row.name, row.children)
          break
        case 'edit'://节点编辑
          if (row.type == 0) {//目录编辑
            that.editCatalogDir(row)
          } else {//服务编辑
            that.editCatalogService(row)
          }
          break
        case 'editQuery'://服务查询信息配置
          that.dialogConfig.config = {
            show: true
          }
          that.dialogConfig.form = {
            serviceId: row.id
          }
          that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editServiceQuery.vue'], resolve)
          break
        case 'editStatistics'://服务统计信息配置
          that.dialogConfig.config = {
            show: true
          }
          that.dialogConfig.form = {
            serviceId: row.id
          }
          that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editServiceStatistics.vue'], resolve)
          break
        case 'delete'://删除节点
          that.deleteCatalogItem(row.id, row.name)
          break
        case 'orderToTop'://排序置顶
          let obj = {
            'id': row.id,
            'sortid': 1
          }
          items.push(obj)
          that.config.catalogData.forEach((ite, i) => {
            if ((ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) && ite.id != row.id) {
              items.push({
                'id': ite.id,
                'sortid': items.length + 1
              })
            }
          })
          that.updateResourceCatalogSort(items)
          break
        case 'orderUp'://排序上移
          let preItem = {}
          let preSortid = row.sortid
          try {
            that.config.catalogData.forEach((ite, i) => {
              if (ite.id == row.id) {
                throw Error()
              } else {
                if (ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) {
                  preSortid = ite.sortid
                  preItem = { 'id': ite.id, 'sortid': row.sortid }
                }
              }
            })
          } catch (err) {
          }
          if (preSortid != row.sortid) {
            items.push(preItem)
            items.push({
              'id': row.id,
              'sortid': preSortid
            })
            that.updateResourceCatalogSort(items)
          }
          break
        case 'orderDown'://排序下移
          let nextItem = {}
          let nextSortid = row.sortid
          let x = 0
          try {
            that.config.catalogData.forEach((ite, i) => {
              if (ite.id == row.id) {
                x = 1
              } else {
                if (ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) {
                  if (x == 1) {
                    nextSortid = ite.sortid
                    nextItem = {
                      'id': ite.id,
                      'sortid': row.sortid
                    }
                    throw Error()
                  }
                }
              }
            })
          } catch (err) {
          }
          if (nextSortid != row.sortid) {
            items.push(nextItem)
            items.push({
              'id': row.id,
              'sortid': nextSortid
            })
            that.updateResourceCatalogSort(items)
          }
          break
        case 'orderToBottom'://排序置底
          that.config.catalogData.forEach((ite, i) => {
            if ((ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) && ite.id != row.id) {
              items.push({
                'id': ite.id,
                'sortid': items.length + 1
              })
            }
          })
          items.push({
            'id': row.id,
            'sortid': items.length + 1
          })
          that.updateResourceCatalogSort(items)
          break
      }
    },
    /**
     * 删除节点
     * @param id 节点id
     * @param name 节点名称
     */
    deleteCatalogItem(id, name) {
      let that = this
      that.dialogConfig.config = {
        title: '删除节点',
        show: true,
        innerHtml: '<span>是否删除节点：' + name + '</span>',
        okBtnText: '删除',
        handleOk: function(form) {
          deleteResourceCatalogItem(form.id).then((res) => {
            bus.$emit('refreshResourceCatalog')
            that.dialogConfig.config.show = false
          }).catch(resp => {
            console.log('updateResourceCatalog', resp.status + ',' + resp.statusText)
          })
        }
      }
      that.dialogConfig.form = {
        operatetype: 'delete',
        id: id
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/defaultDialog.vue'], resolve)
    },
    /**
     * 格式化目录树数据
     * @param parentNodes
     * @param parentId
     * @param catalogData
     * @constructor
     */
    formatCatalogTreeData(parentNodes, parentId, catalogData) {
      let that = this
      for (let i in catalogData) {
        let nodeItem = catalogData[i]
        //2022年3月21日 LQ 数据库里根目录有的为null，有的为''
        if (nodeItem.pid == parentId || (nodeItem.pid == null && parentId == '')) {

          let name = nodeItem.name
          let node = that.getCatalogItemData(nodeItem, false)
          that.formatCatalogTreeData(node.children, node.id, catalogData)

          parentNodes.push(node)
        }
      }
    },
    /**
     * 格式化父级节点
     * @param parentNodes
     * @param parentId
     * @param checkedId
     * @param removeId
     * @param catalogTreeData
     */
    formatParentNodeTreeData(parentNodes, parentId, checkedId, removeId, catalogTreeData) {
      let that = this
      for (let i in catalogTreeData) {
        let treeItem = catalogTreeData[i]
        if (treeItem.type == 0) {
          if (treeItem.pid == parentId && treeItem.id != removeId) {
            let tree = gcf.extend({}, {}, treeItem)
            tree.children = []
            that.formatParentNodeTreeData(tree.children, treeItem.id, checkedId, removeId, treeItem.children)
            parentNodes.push(tree)
          }
        }
      }
    },
    editCatalogDir(row) {
      let that = this
      that.dialogConfig.config = {
        title: '编辑目录',
        show: true,
        itemShow: {
          parentCatalog: true,
          name: true,
          isValid: true,
          roles: true
        },
        okBtnText: '确定'
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editCatalogDir.vue'], resolve)
      that.config.catalogDirTreeData = []
      let rootNode = {
        'label': '根目录',
        'name': '根目录',
        'id': '',
        'value': '',
        'children': []
      }
      that.config.catalogDirTreeData.push(rootNode)
      that.formatParentNodeTreeData(that.config.catalogDirTreeData, '', row.pid, '', that.config.catalogTreeData)
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.catalogDirTreeData,
        portalRoles: that.config.portalRoles
      }
      let pid = row.pid == null ? '' : row.pid
      let parentCatalogName = that.getCatalogDirName(that.config.catalogDirTreeData, pid)
      that.dialogConfig.form = {
        operatetype: 'updateDir',
        parentCatalog: pid,
        parentCatalogName: parentCatalogName,
        isValid: row.isvalid == 0 ? false : true,
        name: row.name,
        roles: row.roleid ? row.roleid.split(',') : [],
        id: row.id,
        enflag:row.enflag,
        explain:row.explain
      }
    },
    editCatalogService(row) {
      let that = this
      that.dialogConfig.config = {
        title: '编辑服务',
        show: true,
        itemShow: {
          isLabel: false
        },
        okBtnText: '确定'
      }
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editCatalogService.vue'], resolve)
      that.config.catalogDirTreeData = []
      let rootNode = {
        'label': '根目录',
        'name': '根目录',
        'id': '',
        'value': '',
        'children': []
      }
      that.config.catalogDirTreeData.push(rootNode)
      that.formatParentNodeTreeData(that.config.catalogDirTreeData, '', row.pid, '', that.config.catalogTreeData)
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.catalogDirTreeData,
        portalRoles: that.config.portalRoles,
        prjTypes: that.config.prjTypes,
        serviceTypes: that.config.serviceTypes
      }
      let pid = row.pid == null ? '' : row.pid
      let parentCatalogName = that.getCatalogDirName(that.config.catalogDirTreeData, pid)
      that.dialogConfig.form = {
        id: row.id,
        operatetype: 'updateService',
        parentCatalog: pid,
        parentCatalogName: parentCatalogName,
        isValid: row.isvalid == 0 ? false : true,
        //isLabel: row.islabel==0?false:true,
        name: row.name,
        serviceType: row.servicetypevalue,
        roles: row.roleid ? row.roleid.split(',') : [],
        date: row.dates,
        url: row.url,
        zmax: row.zmax,
        zmin: row.zmin,
        xmax: row.xmax,
        xmin: row.xmin,
        ymax: row.ymax,
        ymin: row.ymin,
        legend: row.legend,//图例地址
        isAutoLoad: row.autoload == 0 ? false : true,
        prjType: row.sys,
        enflag:row.enflag,
        explain:row.explain
      }
    },
    /**
     * 获取目录节点Item数据对象
     * @param layerItem {} 节点数据
     * @param visible bool 是否可见
     * @returns {*}
     */
    getCatalogItemData(layerItem, visible) {
      return gcf.extend({}, {
        'label': layerItem.name,
        'name': layerItem.name,
        'children': []
      }, layerItem)
    },
    /**
     * 根据id获取节点名称
     * @param catalogData
     * @param id
     * @returns {string}
     */
    getCatalogDirName(catalogData, id) {
      let that = this
      let name = ''
      for (let i in catalogData) {
        let item = catalogData[i]
        if (item.id == id) {
          name = item.name
          break
        } else if (item.children.length > 0) {
          name = that.getCatalogDirName(item.children, id)
          if (name != '') {
            break
          }
        }
      }
      return name
    },
    load(tree, treeNode, resolve) {
    },
    /**
     * 查询目录树数据
     * @param param
     */
    queryCatalog(param) {
      let that = this
      this.loading = true
      listResourceCatalog(param).then(response => {
          that.config.catalogData = response.data.catalogData
          that.config.catalogTreeData = []
          that.formatCatalogTreeData(that.config.catalogTreeData, '', that.config.catalogData)
          that.loading = false
        }
      ).catch(resp => {
        console.log('listResourceCatalog', resp.status + ',' + resp.statusText)
      })
    },
    /**
     * 查询服务类型
     * @param param
     */
    queryServiceType(param) {
      let that = this
      listDict(param).then((res) => {
        that.config.serviceTypes = []
        for (let i in res.data.dictValue) {
          let item = res.data.dictValue[i]
          that.config.serviceTypes.push({
            name: item.itemtext,
            value: item.itemvalue
          })
        }
      }).catch(resp => {
        console.log('listDict', resp.status + ',' + resp.statusText)
      })
    },
    queryPrjType(param) {
      let that = this
      listDict(param).then((res) => {
        that.config.prjTypes = []
        for (let i in res.data.dictValue) {
          let item = res.data.dictValue[i]
          that.config.prjTypes.push({
            name: item.itemtext,
            value: item.itemvalue
          })
        }
      }).catch(resp => {
        console.log('queryDict', resp.status + ',' + resp.statusText)
      })
    },
    queryAllPortalRolesAjax(param) {
      let that = this
      listRole(param).then((res) => {
        that.config.portalRoles = []
        for (let i in res.rows) {
          let role = res.rows[i]
          that.config.portalRoles.push({
            name: role.roleName,
            value: role.roleId
          })
        }
      }).catch(resp => {
        console.log('queryPortalRole', resp.status + ',' + resp.statusText)
      })
    },
    setAllExpand(arr, state) {
      let that = this
      arr.forEach(i => {
        that.$refs.catalogTree.toggleRowExpansion(i, state)
        if (i.children) {
          that.setAllExpand(i.children, state)
        }
      })
    },
    /**
     * 更新排序
     * @param params
     */
    updateResourceCatalogSort(params) {
      let that = this;
      let paramsStr = JSON.stringify(params);
      sortResourceCatalog(paramsStr).then((res) => {
          that.queryCatalog({})
        }).catch(resp => {
        console.log('sortResourceCatalog', resp.status + ',' + resp.statusText)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-table-div {
  ::v-deep .el-button + .el-button {
    margin-left: 0;
  }
}
::v-deep{
  .upload-img-linkText{
    display: inline-block; max-width:200px; margin-left:20px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;
  }
}
</style>
